package com.gec.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gec.domain.User;

@WebFilter("*.action")
public class RoleFilter implements Filter {
    public RoleFilter() {
    }
	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		//获取servletPath
		HttpServletRequest hRequest = (HttpServletRequest)request;
		
		String servletPath = hRequest.getServletPath();
		if(servletPath.equals("/login.action") || servletPath.equals("/loginForm.action")) {
			chain.doFilter(request, response);//不再拦截
		}else {
			
			PrintWriter out = response.getWriter();
			
			HttpSession session = hRequest.getSession();
			User user = (User) session.getAttribute("user");
			//判断
			if(user == null) {
				out.println("请登录后操作<a href='index.html'>登录</a>");
				
				HttpServletResponse res = (HttpServletResponse)response;
				//停留3秒后，跳转到index.html页面
				res.setHeader("refresh", "3;index.html");
			}else {
				//登录了
				chain.doFilter(request, response);
			}
		}
		
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
